package com.leetcode.August;

import javax.swing.tree.TreeNode;

/**
 * @Description: 236. 二叉树的最近公共祖先
 * @Author: Mr.Fxy
 * @CreateTime: 2024-08-06 22:15
 */
public class LC236二叉树的最近公共祖先 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) {
            return root;//返回当前节点
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) {
            return root;//都找到返回当前节点
        }
        return left != null ? left : right;//只有左子树找到递归左子树结果
    }


}
